/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package network;

import bbqtorrent.TorrentManager;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ggroff
 */
public class GererServeur extends Thread{

	private ArrayList<GroupeServeurs> listeGroupe;
	private TorrentManager torrentManager;


	public GererServeur(TorrentManager tm) {  
		System.out.println("GererServeur|construct");
		this.torrentManager = tm;        
		this.listeGroupe = new ArrayList<GroupeServeurs>();        

		this.creerGroupeServeurs(10);

	}

	private void creerGroupeServeurs(int n){
		GroupeServeurs gs;

		for(int i=0; i<n; i++) {
			gs = new GroupeServeurs();
			this.listeGroupe.add(gs);
			gs.start();
		}
	}

	private void waitingForConnections(int port) throws IOException {
		GroupeServeurs min = null;
		ServerSocket ss = new ServerSocket(port);
		Socket sc;
		while (true) {
			min = this.listeGroupe.get(0);
			for (GroupeServeurs gs : this.listeGroupe) {
				if (gs.getSize() < min.getSize()) {
					min = gs;                    
				}
			}

			if(min.getSize() < 50) {
				sc = ss.accept();

				if(sc != null) {
					try {
						min.addServer(new Serveur(min.getIdGroupeServeur(), sc, this.torrentManager));
						System.out.println("GererServeur|waitingForConnections: successful connection");
					} catch (Exception e) {
						System.out.println("GererServeur|waitingForConnections: connection failure");
                        e.printStackTrace();
					}            	
				} else {
					System.out.println("GererServeur|waitingForConnections: connection failure");
				}
			}
		}
	}
	@Override
	public void run () {
		try {
			this.waitingForConnections(8888);
		} catch (IOException e) {
			System.out.println("IOException "+e.getMessage());
		} catch (Exception e) {
			System.out.println("Unexpected exception "+e.getMessage());
		}
	}
}